<template>
  <el-dialog
    :title="textMap[dialogStatus]"
    :visible.sync="dialogFormVisible2"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :fullscreen="false"
  >
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="formData"
      label-position="left"
      label-width="120px"
      style="width: 500px; margin-left:50px;"
    >
      <el-form-item label="租户名" prop="name">
        <el-input v-model="formData.name"/>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description"/>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="formData.type" placeholder="选择租户类型" filterable class="filter-item" style="width:380px">
          <el-option v-for="item in tenantTypeList" :key="item.key" :label="item.value" :value="item.key"/>
        </el-select>
      </el-form-item>
      <el-form-item label="所属租户组" prop="groupId" v-if="formData.type=='common'">
        <el-select v-model="formData.groupId" placeholder="选择租户组" filterable class="filter-item" style="width:380px">
          <el-option v-for="item in tenantGroupList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="关联app" prop="appList">
        <el-select v-model="formData.selectedAppIdList" multiple placeholder="选择app" filterable class="filter-item"
                   style="width:380px">
          <el-option v-for="item in appList" :key="item.id" :label="item.fullname" :value="item.id"/>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible2 = false">
        取消
      </el-button>
      <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
        确认
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import * as apiTenant from '@/api/tenant'
  import * as apiApp from '@/api/app'

  export default {
    name: 'CreateTenant',
    props: ['textMap', 'dialogStatus', 'dialogFormVisible'],
    computed: {
      dialogFormVisible2: {
        get() {
          return this.dialogFormVisible
        },
        set(val) {
          // dialogFormVisible改变由父组件控制
          this.$emit('update:dialogFormVisible', val)
        }
      }
    },
    watch: {
      // 如果 `selfPasswordFlag` 发生改变，这个函数就会运行
      'formData.type': function (newVal, oldVal) {
        if (newVal === 'group') {
          this.formData.groupId = -1
        }
      }
    },
    created() {
      this.getAppList()
      this.getTenantGroupList()
    },
    data() {
      return {
        formData: {
          id: undefined,
          name: undefined,
          description: undefined,
          type: 'common',
          groupId: -1,
          selectedAppIdList: []
        },
        tenantTypeList: [
          { key: 'common', value: '一般租户' },
          { key: 'group', value: '租户组' }
        ],
        appList: [],
        tenantGroupList: [],
        rules: {
          name: [{ required: true, message: '租户名必填', trigger: 'blur' }],
          description: [{ required: true, message: '描述必填', trigger: 'blur' }],
          type: [{ required: true, message: '租户类型必填', trigger: 'blur' }]
        }
      }
    },
    methods: {
      async getTenantGroupList() {
        const { content } = await apiTenant.getList({ // 查询列表时的参数对象
          pageNumber: 1,
          pageSize: 500,
          type: 'group'
        })
        this.tenantGroupList = content.list
        this.tenantGroupList.unshift({ id: -1, name: '无' })
      },

      async getAppList() {
        const { content } = await apiApp.getList({ // 查询列表时的参数对象
          pageNumber: 1,
          pageSize: 500
        })
        this.appList = content.list
      },
      clearFormData() {//清除 this.formData数据
        Object.keys(this.formData).forEach(key => {
          this.formData[key] = undefined
        })
      },
      setCurrentRow(currentRowData) {// 修改 某条记录时 获取记录信息
        this.formData.id = currentRowData.id
        this.formData.name = currentRowData.name
        this.formData.description = currentRowData.description
        this.formData.type = currentRowData.type
        this.formData.groupId = currentRowData.groupId
        this.formData.selectedAppIdList = []
        const appList = currentRowData.appList
        appList.forEach((app) => {
          this.formData.selectedAppIdList.push(app.id)
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            apiTenant.createOrUpdate(this.formData).then(() => {
              // 通知父组件刷新列表数据
              this.$emit('on-fresh-list')
              this.dialogFormVisible2 = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.formData)
            apiTenant.createOrUpdate(tempData).then(() => {
              // 通知父组件刷新列表数据
              this.$emit('on-fresh-list')
              this.dialogFormVisible2 = false
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
